package com.dm.cloud.configurations.password;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dm.cloud.api.dto.Users;
import com.dm.cloud.configurations.exceptions.NonUsernameException;
import com.dm.cloud.dao.UsersDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserDetailServiceImpl implements UserDetailsService  {

    @Autowired
    private UsersDao userDao;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //获取本地用户
        QueryWrapper<Users> userQueryWrapper =new QueryWrapper<>();
        userQueryWrapper.eq("user_name",userName).eq("delete_flag",0);
        Users user = userDao.selectOne(userQueryWrapper);
        if(user != null){
            //判断锁定次数是否超过三次
            int lockValue = null == user.getLockFlag()?0:user.getLockFlag();
            if(lockValue>=3){
                throw  new LockedException("密码尝试超过三次，账户已被锁定!");
            }

            UserDetails userr = User.builder()
                    .username(user.getUserName())
                    .password(user.getPassword())
                    .authorities(AuthorityUtils.createAuthorityList("ADMIN"))
                    .build();

            return userr;
        }else{
            throw  new NonUsernameException("用户不存在");
        }
    }
}